package com.uduemc.biso.node.web.controller;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.extities.center.Host;
import com.uduemc.biso.core.extities.center.Site;
import com.uduemc.biso.core.extities.center.SysLanguage;
import com.uduemc.biso.core.utils.HttpUtil;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.entities.HDomain;
import com.uduemc.biso.node.core.entities.SPage;
import com.uduemc.biso.node.core.utils.SiteUrlUtil;
import com.uduemc.biso.node.web.service.SRHtmlCacheService;
import com.uduemc.biso.node.web.service.byfeign.DomainService;
import com.uduemc.biso.node.web.service.byfeign.HostService;
import com.uduemc.biso.node.web.service.byfeign.LanguageService;
import com.uduemc.biso.node.web.service.byfeign.SiteService;

@RestController
@RequestMapping("/website")
public class WebsiteController {

//	private final static Logger logger = LoggerFactory.getLogger(SiteApiController.class);

	@Autowired
	private SRHtmlCacheService sRHtmlCacheServiceImpl;

	@Autowired
	private DomainService domainServiceImpl;

	@Autowired
	private SiteService siteServiceImpl;

	@Autowired
	private HostService hostServiceImpl;

	@Autowired
	private LanguageService languageServiceImpl;

	/**
	 * 清除 srhtml 缓存
	 * 
	 * @return
	 */
	@PostMapping("/srhtml/cache-clear")
	public RestResult cacheClear(@RequestBody SPage sPage) {
		sRHtmlCacheServiceImpl.cacheClear(sPage);
		return RestResult.ok(1);
	}

	/**
	 * 清除 重置 缓存
	 * 
	 * @param template
	 * @return
	 * @throws IOException
	 * @throws JsonProcessingException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	@PostMapping("/srhtml/cache-reset")
	public RestResult cacheReset(@RequestBody SPage sPage)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		Long hostId = sPage.getHostId();
		Host host = hostServiceImpl.getHostById(hostId);
		if (host == null) {
			return RestResult.error();
		}
		Long siteId = sPage.getSiteId();
		Site site = siteServiceImpl.getOkSiteList(hostId, siteId);
		if (site == null) {
			return RestResult.error();
		}

		sRHtmlCacheServiceImpl.cacheClear(sPage);

		HDomain hDomain = domainServiceImpl.getDefaultDataByHostId(hostId);
		String path = SiteUrlUtil.getPath(sPage);
		SysLanguage languageBySite = languageServiceImpl.getLanguageBySite(site);

		String url = "http://" + hDomain.getDomainName() + "/" + languageBySite.getLanNo() + path;
		HttpUtil.get(url);
		return RestResult.ok(1);
	}

}
